#include "BucketsService.h"

#include "../common/YXLog.h"
#include "../common/YXResult.h"
#include "../common/YXTime.h"
#include "../mapper/BucketsMapper.h"
#include "../utils/BucketsAccess.h"


YXResult * postBucket(char *bucketName) {
    char* err;

    // 构建数据
    char* createdTime = yx_time_get_local_date_time();
    MYSQLResult* result = insertBucket(bucketName, BUCKET_DEFAULT_ACCESS_POLICY, createdTime);
    if (result->type == MYSQL_RESULT_ERROR) {
        err = yxMYSQLResultGetErrMsg(result);
        yxMYSQLResultFree(result);
        return YXResultUtils.error(err);
    }
    return YXResultUtils.success(NULL);
}

YXResult *getBuckets() {
    const char *err;

    // 从数据库获取桶列表
    MYSQLResult *result = selectBuckets();
    if (result->type == MYSQL_RESULT_ERROR) {
        err = yxMYSQLResultGetErrMsg(result);
        yxMYSQLResultFree(result);
        return YXResultUtils.error(err);
    }
    // 获取桶列表
    yxArray  *buckets  = yxMYSQLResultGetArrayValue(result);
    YXResult *yxResult = YXResultUtils.success(buckets);
    // 释放资源
    yxMYSQLResultFreeNotValue(result);

    return yxResult;
}

YXResult *getBucketSummary(char *bucketName) {
    char *err;

    MYSQLResult *result = selectBucketSummary(bucketName);
    if (result->type == MYSQL_RESULT_ERROR) {
        err = yxMYSQLResultGetErrMsg(result);
        yxMYSQLResultFree(result);
        return YXResultUtils.error(err);
    }
    yxObject *bucketSummary = yxMYSQLResultGetObjectValue(result);
    yxMYSQLResultFreeNotValue(result);
    return YXResultUtils.success(bucketSummary);
}